package cn.nexttec.noteplayer.service

import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Binder
import android.os.Environment
import android.os.IBinder
import cn.nexttec.noteplayer.common.SCAN
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.common.getAppRootOfSdCardRemovable
import cn.nexttec.noteplayer.common.walk
import cn.nexttec.noteplayer.databases.dao.VideoFileDao
import cn.nexttec.noteplayer.events.FileScanDoneEvent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import java.io.File
import javax.inject.Inject

@AndroidEntryPoint
class FileScanService : Service() {
    private val job = SupervisorJob()
    private val scope = CoroutineScope(Dispatchers.IO + job)

    @Inject
    lateinit var videoFileDao: VideoFileDao

    companion object {
        private const val TAG = "FileScanService"

        fun bind(
            context: Context,
            onConnected: ((FileScanService) -> Unit)? = null
        ): ServiceConnection {
            val con = object : ServiceConnection {
                override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
                    val binder = p1 as LocalBinder
                    onConnected?.invoke(binder.service)
                }

                override fun onServiceDisconnected(p0: ComponentName?) = Unit

            }
            context.bindService(
                Intent(context, FileScanService::class.java),
                con, Context.BIND_AUTO_CREATE
            )
            return con
        }
    }

    override fun onBind(intent: Intent): IBinder {
        return LocalBinder()
    }

    inner class LocalBinder() : Binder() {
        val service = this@FileScanService
    }

    override fun onCreate() {
        super.onCreate()
        scanVideoFiles()
    }

    fun scanVideoFiles() {
        SCAN debug "开始扫描文件"
        val paths = ArrayList<String>()
        paths.add(Environment.getExternalStorageDirectory().absolutePath)

        scope.launch {
            val sdcardPath = this@FileScanService.getAppRootOfSdCardRemovable()
            sdcardPath?.let {
                paths.addAll(it)
            }

            videoFileDao.clearAll()
            paths.forEach {
                TAG debug "扫描 $it"
                walk(it, onVideosFound = {
                    it.forEach { video ->
                        val folder = "\uD83D\uDCC1"
                        val videocassette = "\uD83D\uDCFC"
                        videoFileDao.insertVideoFile(video)
                        TAG debug "${if (video.isVideoFile) videocassette else folder} ${video.name}"
                    }
                })
            }

            withContext(Dispatchers.Main){
                EventBus.getDefault().post(FileScanDoneEvent)
            }
        }
    }
}